﻿using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml.Linq;
using Microsoft.Office.Interop.Outlook;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.Server;
using Outlook.WorkItems.Extension.Manager.TeamPortal;
using Outlook.WorkItems.Extension.Managers;
using System;

namespace Outlook.WorkItems.Extension.Manager.TeamProjectManager
{
    public class UploadAttachmentsAction : IAction<MailItem>
    {
        /// <summary>
        /// Constructor
        /// </summary>
        public UploadAttachmentsAction()
        {
            DestinationPath = "";
            FileExtensions = "";
        }

        /// <summary>
        /// Destination path to team portal
        /// </summary>
        public string DestinationPath { get; set; }
        /// <summary>
        /// File extensions to consider
        /// </summary>
        public string FileExtensions { get; set; }

        #region IAction Members

        /// <summary>
        /// Deserialize xml to UploadAttachmentsAction
        /// </summary>
        /// <param name="action"></param>
        public void DeserializeAction(System.Xml.Linq.XElement action)
        {
            DestinationPath = action.Attribute("destinationPath").Value;
            if (action.Attribute("fileExtensions") != null)
            {
                FileExtensions = action.Attribute("fileExtensions").Value;
            }
        }

        /// <summary>
        /// Execute action 
        /// </summary>
        /// <param name="item"></param>
        public void DoAction(MailItem item)
        {
            if (item == null)
                return;

            var folder = (MAPIFolder)item.Parent;
            if (!TeamProjectLinksManager.ContainsTeamProjectLink(folder.EntryID))
                return;

            TeamProjectLink link = TeamProjectLinksManager.GetTeamProjectLink(folder.EntryID);

            var tfs = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri(link.TeamServerUri));

            var registration = (IRegistration)tfs.GetService(typeof(IRegistration));

            var entries = registration.GetRegistrationEntries("Wss");

            string baseSiteUrl = null;
            foreach (ServiceInterface si in entries[0].ServiceInterfaces)
            {
                if (si.Name == "BaseSiteUrl")
                    baseSiteUrl = si.Url;
            }

            string projectBaseUrl = baseSiteUrl + "/" + link.TeamProjectName;
            
            string[] extensions = FileExtensions.Split(',');

            foreach (Attachment att in item.Attachments)
            {
                bool isOk = false;
                if (extensions == null || extensions.Length == 0)
                    isOk = true;
                else
                    isOk = (from ex in extensions
                            where att.FileName.EndsWith("." + ex.Trim())
                            select ex).Any();

                if (isOk)
                {
                    string appDataFolder = Path.GetTempPath();
                    string path = appDataFolder + "\\" + att.FileName;
                    att.SaveAsFile(path);

                    string fullName = DestinationPath;
                    //fullName += "/" + att.FileName;
                    Dictionary<string, object> properties = new Dictionary<string, object>();
                    properties.Add("Title", att.FileName);

                    string destinationPath = projectBaseUrl + fullName.Substring(fullName.IndexOf('/', 7), fullName.Length - fullName.IndexOf('/', 7));
                    destinationPath += "/" + att.FileName;
                    DocLibHelper.Upload(destinationPath, File.ReadAllBytes(path), properties);
                }
            }
        }

        /// <summary>
        /// Serialize xml to UploadAttachmentsAction
        /// </summary>
        public XNode SerializeAction()
        {
            return new XElement("UploadAttachmentsAction",
                        new XAttribute("destinationPath", DestinationPath),
                        new XAttribute("fileExtensions", FileExtensions)
                        );
        }
        
        #endregion
    }
}
